package com.example.testrxjava.fragment.home;

import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.testrxjava.ArticleDetailsActivity;
import com.example.testrxjava.R;
import com.example.testrxjava.activity.search.SearchActivity;
import com.example.testrxjava.adapter.HomeListAdapter;
import com.example.testrxjava.base.BaseFragment;
import com.example.testrxjava.util.Action;
import com.example.testrxjava.util.BaseResponse;
import com.example.testrxjava.util.CollectSucessCallback;
import com.example.testrxjava.util.CommUtil;
import com.example.testrxjava.util.ConTract;
import com.example.testrxjava.util.UnCollectSuccessCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 项目名称：TestRxjava
 *
 * @Author 郭迎辉
 * Create by 10:12 on 2019/4/18.
 * Describe:
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.searchTv)
    EditText mSearchTv;

    @BindView(R.id.searchIv)
    ImageView mSearchIv;

//    @BindView(R.id.home_banner)
    Banner banner;
    @BindView(R.id.home_Recy)
    RecyclerView recyclerView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout refreshLayout;
//    private Banner banner;
//    private RecyclerView recyclerView;
    List<String> bannerTitles;
    List<String> bannerImages;
    List<String> bannerUrls;
    private List<HomeListBean.DataBean.DatasBean> data;
    View bannerView;
    private HomeListAdapter newAdapter;
    private int page=0;//分页
    @Override
    protected void initData() {

        Action.getInstance().getHomeBanner(new HomeBannerSucessCallBack() {
            @Override
            public void bannerSucess(BannerBean bean) {
//               banner.setImages(bean.getData());
                if(bean.getData()!=null){
                    bannerImages.clear();
                    bannerTitles.clear();
                    bannerUrls.clear();
                }

                for (int i = 0; i < bean.getData().size(); i++) {
                    bannerImages.add(bean.getData().get(i).getImagePath());
                    bannerUrls.add(bean.getData().get(i).getUrl());
                    bannerTitles.add(bean.getData().get(i).getTitle());

                    Log.e("图片地址===",bean.getData().get(i).getImagePath());
                    Log.e("图片标题===",bean.getData().get(i).getTitle());
                }
//                banner.setImages(dataBeans);
//                banner.start();
                    banner.setImageLoader(new GlideImageLoader())
                        .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                            .setImages(bannerImages)
                            .setBannerAnimation(Transformer.Default)
                            .setBannerTitles(bannerTitles)
                            .setIndicatorGravity(BannerConfig.RIGHT)//设置指示器位置，右边
                            .setDelayTime(3000)//设置轮播事件间隔
                            .setOnBannerListener(new OnBannerListener() {
                                @Override
                                public void OnBannerClick(int position) {
                                    ArticleDetailsActivity.startActivityByFragment(getActivity(),
                                            HomeFragment.this,
                                            bannerUrls.get(position),
                                            bannerTitles.get(position));
                                }
                            })
                            .start();





            }

            @Override
            public void bannerFail(String message) {
                CommUtil.Toast(getActivity(),message);
            }
        });

        Action.getInstance().getHomeList(0, new HomeListSucessCallback() {
            @Override
            public void homeListSucess(HomeListBean bean) {

                data=bean.getData().getDatas();
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//                HomeListAdapter adapter=new HomeListAdapter(getActivity(),data);

                for (int i = 0; i < data.size(); i++) {
                    Log.e("是否收藏==",data.get(i).getTitle()+"==="+data.get(i).isCollect());
                }

                newAdapter=new HomeListAdapter(R.layout.item_home_list,data);
                newAdapter.openLoadAnimation();
                newAdapter.addHeaderView(bannerView);
                recyclerView.setAdapter(newAdapter);

                newAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        Log.e("文章作者","文章详情："+data.get(position).getAuthor());
                        ArticleDetailsActivity.startActivityForResultByFragment(getActivity(),
                                HomeFragment.this,
                                data.get(position).getLink(),
                                data.get(position).getTitle(),
                                data.get(position).getId(),
                                data.get(position).isCollect(),
                                ConTract.REQUEST_ARTICLE_ACTIVITY);


                    }
                });
                newAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(final BaseQuickAdapter adapter, final View view, final int position) {
                        if(!CommUtil.isLogin(getActivity())){
                            CommUtil.Toast(getActivity(),"请先登录~");
                            return;
                        }


                        if (data.get(position).isCollect()) {//如果已经收藏文章，取消收藏
                                Action.getInstance().unCollect(getActivity(), data.get(position).getId()+"", new UnCollectSuccessCallback() {
                                    @Override
                                    public void unCollectSuccess(BaseResponse response) {
                                        Log.e("errorcode===",response.getErrorCode()+"");
                                        if(response.getErrorCode()==0){
                                            data.get(position).setCollect(false);
                                            adapter.notifyDataSetChanged();
                                        }
                                    }

                                    @Override
                                    public void unCollectFail(String error) {
                                        CommUtil.Toast(getActivity(),error);
                                    }
                                });



                        } else {//否则添加收藏

                            Log.e("文章收藏==标题", data.get(position).getTitle());
                            Action.getInstance().collect(getActivity(), data.get(position).getId() + "", new CollectSucessCallback() {
                                @Override
                                public void collectSucess(BaseResponse result) {
                                    Log.e("收藏文章==", result.getErrorCode() + "");
//                                adapter.notifyDataSetChanged();
//                                Log.e("id",view.getId()+"");
//                                view.getV
                                    if(result.getErrorCode()==0){
                                        data.get(position).setCollect(true);
                                        adapter.notifyDataSetChanged();
                                    }

                                }

                                @Override
                                public void collectFail(String error) {
                                    CommUtil.Toast(getActivity(),error);
                                }
                            });
                        }
                    }
                });

            }

            @Override
            public void homeListFail(String message) {

            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                data.clear();
                page=0;
                Action.getInstance().getHomeList(page, new HomeListSucessCallback() {
                    @Override
                    public void homeListSucess(HomeListBean bean) {
                        Log.e("----",page+"");
                        data.addAll(bean.getData().getDatas());
                        newAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void homeListFail(String message) {
                        CommUtil.Toast(getActivity(),message);
                    }
                });
            refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                Action.getInstance().getHomeList(page, new HomeListSucessCallback() {
                    @Override
                    public void homeListSucess(HomeListBean bean) {
                        if(bean==null)page--;
                        Log.e("----",page+"");
                        data.addAll(bean.getData().getDatas());
                        newAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void homeListFail(String message) {
                        CommUtil.Toast(getActivity(),message);
                    }
                });
                refreshlayout.finishLoadmore();
            }
        });


        mSearchTv.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {
                toSearchActivity();
            }
        });

    }

    @Override
    protected View initView() {

        View view= LayoutInflater.from(getActivity()).inflate(R.layout.home_fragment,null);
//        dataBeans=new ArrayList<String>();
        bannerView=LayoutInflater.from(getActivity()).inflate(R.layout.banner_layout, null);
        banner=bannerView.findViewById(R.id.banner);
        data=new ArrayList<HomeListBean.DataBean.DatasBean>();
        bannerImages=new ArrayList<String>();
        bannerTitles=new ArrayList<String>();
        bannerUrls=new ArrayList<String>();



//

        return view;
    }



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void toSearchActivity() {
        Intent intent = new Intent(getActivity(), SearchActivity.class);

//        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MyApplication.getInstance(),
//                Pair.create(mSearchTv, getString(R.string.share_edit)),
//                Pair.create(mSearchIv, getString(R.string.share_image))
//        );
        ActivityOptionsCompat options= ActivityOptionsCompat .makeCustomAnimation(getActivity(),R.anim.anim_animo_alph_open,R.anim.anim_animo_alph_close);
        startActivity(intent, options.toBundle());
    }

}
